# PPH 智能更新脚本 v1.2.1
# 用法: .\smart-update.ps1 [-Force] [-SkipBuild]

param(
    [switch]$Force,      # 强制重启所有服务
    [switch]$SkipBuild,  # 跳过构建步骤
    [switch]$Help        # 显示帮助信息
)

# 显示帮助信息
if ($Help) {
    Write-Host @"
PPH 智能更新脚本 v1.2.1

用法:
  .\smart-update.ps1              # 智能更新（推荐）
  .\smart-update.ps1 -Force       # 强制重启所有服务
  .\smart-update.ps1 -SkipBuild   # 跳过构建步骤
  .\smart-update.ps1 -Help        # 显示此帮助信息

功能:
- 自动检测代码变更类型
- 按需安装依赖和构建前端
- 智能重启相关服务
- 最小化服务中断时间

"@ -ForegroundColor Green
    exit 0
}

Write-Host "🚀 PPH 智能更新开始..." -ForegroundColor Green
Write-Host "📅 更新时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Gray

# 检查是否在正确的目录
$expectedPath = "D:\PPH-Production-System\PPH-Production-Deploy"
if (-not (Test-Path $expectedPath)) {
    Write-Host "❌ 错误: 未找到部署目录 $expectedPath" -ForegroundColor Red
    Write-Host "请确保脚本在正确的服务器环境中运行" -ForegroundColor Yellow
    exit 1
}

# 切换到部署目录
cd $expectedPath
Write-Host "📁 工作目录: $expectedPath" -ForegroundColor Blue

# 1. 拉取更新
Write-Host "`n🔄 步骤 1: 拉取最新代码..." -ForegroundColor Cyan
try {
    git fetch --all --prune
    git checkout master
    git pull --ff-only
    Write-Host "✅ 代码更新完成" -ForegroundColor Green
} catch {
    Write-Host "❌ 代码更新失败: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 显示最新提交信息
Write-Host "`n📋 最新提交:" -ForegroundColor Gray
git log --oneline -3

# 2. 检测变更
Write-Host "`n🔍 步骤 2: 检测代码变更..." -ForegroundColor Cyan
$frontendSrcChanged = git diff HEAD~2 --name-only | findstr "app/frontend/src"
$backendChanged = git diff HEAD~2 --name-only | findstr "app/backend"
$managementChanged = git diff HEAD~2 --name-only | findstr "management"
$packageChanged = git diff HEAD~2 --name-only | findstr "package.json"
$configChanged = git diff HEAD~2 --name-only | findstr "config/"

Write-Host "🔍 变更检测结果:" -ForegroundColor Cyan
$hasChanges = $false
if ($frontendSrcChanged) { 
    Write-Host "  📱 前端源码有变更" -ForegroundColor Yellow
    $hasChanges = $true
}
if ($backendChanged) { 
    Write-Host "  ⚙️ 后端代码有变更" -ForegroundColor Yellow
    $hasChanges = $true
}
if ($managementChanged) { 
    Write-Host "  🔧 管理端代码有变更" -ForegroundColor Yellow
    $hasChanges = $true
}
if ($packageChanged) { 
    Write-Host "  📦 依赖配置有变更" -ForegroundColor Yellow
    $hasChanges = $true
}
if ($configChanged) { 
    Write-Host "  ⚙️ 配置文件有变更" -ForegroundColor Yellow
    $hasChanges = $true
}

if (-not $hasChanges) {
    Write-Host "  ℹ️ 未检测到需要处理的代码变更" -ForegroundColor Green
}

# 3. 按需安装依赖
if ($packageChanged -and -not $SkipBuild) {
    Write-Host "`n📦 步骤 3: 安装依赖..." -ForegroundColor Cyan
    try {
        Write-Host "  安装后端依赖..." -ForegroundColor Blue
        cd app\backend
        npm ci --only=production
        
        Write-Host "  安装管理端依赖..." -ForegroundColor Blue
        cd ..\..\management
        npm ci --only=production
        cd ..
        
        Write-Host "✅ 依赖安装完成" -ForegroundColor Green
    } catch {
        Write-Host "❌ 依赖安装失败: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "💡 建议: 手动执行 npm install --production" -ForegroundColor Yellow
    }
} else {
    if ($SkipBuild) {
        Write-Host "`n⏭️ 跳过依赖安装（-SkipBuild 参数）" -ForegroundColor Yellow
    } else {
        Write-Host "`n⏭️ 跳过依赖安装（无 package.json 变更）" -ForegroundColor Green
    }
}

# 4. 按需构建前端
if ($frontendSrcChanged -and -not $SkipBuild) {
    Write-Host "`n🎨 步骤 4: 构建前端..." -ForegroundColor Cyan
    try {
        cd app\frontend
        npm run build
        cd ..\..
        Write-Host "✅ 前端构建完成" -ForegroundColor Green
    } catch {
        Write-Host "❌ 前端构建失败: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "💡 建议: 手动执行 npm run build" -ForegroundColor Yellow
    }
} else {
    if ($SkipBuild) {
        Write-Host "`n⏭️ 跳过前端构建（-SkipBuild 参数）" -ForegroundColor Yellow
    } else {
        Write-Host "`n⏭️ 跳过前端构建（无前端源码变更）" -ForegroundColor Green
    }
}

# 5. 智能重启服务
Write-Host "`n🔄 步骤 5: 重启服务..." -ForegroundColor Cyan
$restartCount = 0

if ($Force) {
    Write-Host "🔄 强制重启所有服务..." -ForegroundColor Yellow
    npx pm2 restart all
    $restartCount = 3
} else {
    if ($backendChanged) { 
        Write-Host "  重启后端服务..." -ForegroundColor Blue
        npx pm2 restart pph-backend
        $restartCount++
    }
    if ($frontendSrcChanged) { 
        Write-Host "  重启前端服务..." -ForegroundColor Blue
        npx pm2 restart pph-frontend
        $restartCount++
    }
    if ($managementChanged) { 
        Write-Host "  重启管理端服务..." -ForegroundColor Blue
        npx pm2 restart pph-management
        $restartCount++
    }
    if ($configChanged) { 
        Write-Host "  配置文件变更，重启所有服务..." -ForegroundColor Yellow
        npx pm2 restart all
        $restartCount = 3
    }
}

if ($restartCount -eq 0) {
    Write-Host "  ℹ️ 无需重启服务" -ForegroundColor Green
} else {
    Write-Host "✅ 服务重启完成（重启了 $restartCount 个服务）" -ForegroundColor Green
}

# 保存 PM2 配置
npx pm2 save | Out-Null
Write-Host "💾 PM2 配置已保存" -ForegroundColor Green

# 6. 验证服务状态
Write-Host "`n🔍 步骤 6: 验证服务状态..." -ForegroundColor Cyan
npx pm2 ls

# 7. 健康检查
Write-Host "`n🏥 步骤 7: 健康检查..." -ForegroundColor Cyan
try {
    $backendHealth = Invoke-RestMethod -Uri "http://localhost:3011/api/health" -TimeoutSec 5
    Write-Host "✅ 后端服务健康" -ForegroundColor Green
} catch {
    Write-Host "⚠️ 后端服务健康检查失败" -ForegroundColor Yellow
}

try {
    $managementHealth = Invoke-RestMethod -Uri "http://localhost:3012/api/health" -TimeoutSec 5
    Write-Host "✅ 管理端服务健康" -ForegroundColor Green
} catch {
    Write-Host "⚠️ 管理端服务健康检查失败" -ForegroundColor Yellow
}

# 完成
Write-Host "`n🎉 更新完成！" -ForegroundColor Green
Write-Host "📅 完成时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Gray
Write-Host "`n💡 提示:" -ForegroundColor Cyan
Write-Host "  - 如果前端有更新，建议在浏览器按 Ctrl+F5 刷新缓存" -ForegroundColor Gray
Write-Host "  - 可以访问 http://localhost:3010 查看前端应用" -ForegroundColor Gray
Write-Host "  - 可以访问 http://localhost:3012 查看管理界面" -ForegroundColor Gray
